<?php

/**
 * Radcodes - SocialEngine Module
 *
 * @category   Application_Extensions
 * @package    Game
 * @copyright  Copyright (c) 2009-2010 Radcodes LLC (http://www.radcodes.com)
 * @license    http://www.radcodes.com/license/
 * @version    $Id$
 * @author     Vincent Van <vincent@radcodes.com>
 */
 
 
class Game_AdminManageController extends Core_Controller_Action_Admin
{
  
  public function init()
  {
    set_time_limit(0);
    if (!Engine_Api::_()->game()->checkLicense()) {
      return $this->_redirectCustom(array('route'=>'admin_default', 'module'=>'game', 'controller'=>'settings'));
    }
    
    if( !Engine_Api::_()->core()->hasSubject() )
    {
      if( 0 !== ($game_id = (int) $this->_getParam('game_id')) &&
          null !== ($game = Engine_Api::_()->getItem('game', $game_id)) )
      {
        Engine_Api::_()->core()->setSubject($game);
      }
    }

    $this->_helper->requireSubject->setActionRequireTypes(array(
      'featured' => 'game',
      'sponsored' => 'game',
      'delete' => 'game',
      'edit' => 'game',
      'preview' => 'game',
      'download' => 'game',
      'remove' => 'game',
    ));
    
    $this->loadNavigation();
  }
  
  protected function loadNavigation()
  {
    $this->view->navigation = $navigation = Engine_Api::_()->getApi('menus', 'core')
      ->getNavigation('game_admin_main', array(), 'game_admin_main_manage');
  }
  
  public function indexAction()
  {

    $this->view->formFilter = $formFilter = new Game_Form_Admin_Manage_Filter();

    // Process form
    $values = array();
    if($formFilter->isValid($this->_getAllParams()) ) {
      $values = $formFilter->getValues();
    }
    $values = Engine_Api::_()->game()->filterEmptyParams($values);
    
    $this->view->formValues = $values;

    $this->view->assign($values);
   
    $this->view->params = $values;
    
    if (!@$values['limit']) {
      $values['limit'] = 20;
    }
    
    $this->view->paginator = Engine_Api::_()->game()->getGamesPaginator($values);
    //$this->view->paginator->setItemCountPerPage(100);
    $this->view->paginator->setCurrentPageNumber($this->_getParam('page',1));
    
  }
  
  
  public function createAction()
  {
    $viewer = Engine_Api::_()->game()->getDefaultOwner();

    $this->view->form = $form = new Game_Form_Admin_Game_Create();
    
    if (!$this->getRequest()->isPost())
    {
      return;
    }
    
    if (!$form->isValid($this->getRequest()->getPost()))
    {
      return;
    }

    $values = $form->getValues();
    

    $table = Engine_Api::_()->getItemTable('game');
    $db = $table->getAdapter();
    $db->beginTransaction();

    try
    {     
      $values['user_id'] = $viewer->getIdentity();

      $game = $table->createRow();
      $game->setFromArray($values);
      $game->save();

      
      // Add tags
      $tags = preg_split('/[,]+/', $values['keywords']);
      $tags = array_filter(array_map("trim", $tags));
      $game->tags()->addTagMaps($viewer, $tags);

      $customfieldform = $form->getSubForm('fields');
      $customfieldform->setItem($game);
      $customfieldform->saveValues();

      // Set photo
      if( !empty($values['photo']) ) 
      {
        $game->setPhoto($form->photo);
      }      
      if (!empty($values['swf_file'])) {
        $game->setSwf($form->swf_file);
      }
      
      // CREATE AUTH STUFF HERE
      $auth = Engine_Api::_()->authorization()->context;  
      $roles = array('owner', 'owner_member', 'owner_member_member', 'owner_network', 'registered', 'everyone');

      $auth_keys = array(
        'view' => 'everyone',
        'comment' => 'registered',
      );
      
      foreach ($auth_keys as $auth_key => $auth_default)
      {
        $auth_value = isset($values['auth_'.$auth_key]) ? $values['auth_'.$auth_key] : $auth_default;
        $authMax = array_search($auth_value, $roles);
        
        foreach( $roles as $i => $role )
        {
          $auth->setAllowed($game, $role, $auth_key, ($i <= $authMax));
        }
      }

      
      // Add activity
      $action = Engine_Api::_()->getDbtable('actions', 'activity')->addActivity($viewer, $game, 'game_new');
      if ($action != null)
      {
        Engine_Api::_()->getDbtable('actions', 'activity')->attachActivity($action, $game);
      }
      
      // Commit
      $db->commit();
      
      return $this->_redirectCustom(array('route'=>'admin_default', 'module'=>'game', 'controller'=>'manage'));
    }

    catch( Exception $e )
    {
      $db->rollBack();
      throw $e;
    }
    
  }
  
  public function featuredAction()
  {
    // In smoothbox
    $this->view->game = $game = Engine_Api::_()->core()->getSubject('game');
    
    // Check post
    if( $this->getRequest()->isPost())
    {
      $db = Engine_Db_Table::getDefaultAdapter();
      $db->beginTransaction();

      try
      {       
        $game->featured = $this->_getParam('featured') == 'yes' ? 1 : 0;
        $game->save();
        
        $db->commit();
      }

      catch( Exception $e )
      {
        $db->rollBack();
        throw $e;
      }

      $this->_forward('success', 'utility', 'core', array(
          'smoothboxClose' => 10,
          'parentRefresh'=> 10,
          'messages' => array(Zend_Registry::get('Zend_Translate')->_('Changes saved'))
      ));
    }
  }
  
  public function sponsoredAction()
  {
    // In smoothbox
    $this->view->game = $game = Engine_Api::_()->core()->getSubject('game');
    // Check post
    if( $this->getRequest()->isPost())
    {
      $db = Engine_Db_Table::getDefaultAdapter();
      $db->beginTransaction();

      try
      {
        $game->sponsored = $this->_getParam('sponsored') == 'yes' ? 1 : 0;
        $game->save();
        
        $db->commit();
      }

      catch( Exception $e )
      {
        $db->rollBack();
        throw $e;
      }

      $this->_forward('success', 'utility', 'core', array(
          'smoothboxClose' => 10,
          'parentRefresh'=> 10,
          'messages' => array(Zend_Registry::get('Zend_Translate')->_('Changes saved'))
      ));
    }
  }
  
  public function updateStatusAction()
  {
    // In smoothbox
    $this->view->game = $game = Engine_Api::_()->core()->getSubject('game');
    $status = $this->_getParam('status');
    
    if( !$this->getRequest()->isPost() || !$status) {
      return;
    }    
    
    
    if (array_key_exists($status, Game_Form_Helper::getStatuses()) && $game->status != $status) {
      $game->status = $status;
      $game->save();
    }
    
      $this->_forward('success', 'utility', 'core', array(
          'smoothboxClose' => 10,
          'parentRefresh'=> 10,
          'messages' => array(Zend_Registry::get('Zend_Translate')->_('Changes saved'))
      ));
  }
  
  
  public function editAction()
  {
    $viewer = Engine_Api::_()->user()->getViewer();
    $this->view->game = $game = Engine_Api::_()->core()->getSubject('game');
    

    $this->view->form = $form = new Game_Form_Admin_Game_Edit(array(
      'item' => $game,
    ));

    

    $auth = Engine_Api::_()->authorization()->context;
    $roles = array('owner', 'owner_member', 'owner_member_member', 'owner_network', 'registered', 'everyone');
    $auth_keys = array(
      'view' => 'everyone',
      'comment' => 'registered',
    );
    
    // Save game entry
    if( !$this->getRequest()->isPost() )
    {     
      foreach ($auth_keys as $auth_key => $auth_default)
      {
        $auth_field = 'auth_'.$auth_key;
        
        foreach( $roles as $i => $role )
        {
          if (isset($form->$auth_field->options[$role]) && 1 === $auth->isAllowed($game, $role, $auth_key))
          {
            $form->$auth_field->setValue($role);
          }
        }
      }
      
      $form->populate($game->toArray());

      return;
    }
        
    if( !$form->isValid($this->getRequest()->getPost()) )
    {
      return;
    }


    // Process

    // handle save for tags
    $values = $form->getValues();
    $tags = preg_split('/[,]+/', $values['keywords']);
    $tags = array_filter(array_map("trim", $tags));

    
    $db = Engine_Db_Table::getDefaultAdapter();
    $db->beginTransaction();
    try
    {

      $game->setFromArray($values);
      $game->modified_date = date('Y-m-d H:i:s');

      $game->tags()->setTagMaps($game->getOwner(), $tags);
      $game->save();

      // Set photo
      if (!empty($values['photo']) ) {
        $game->removePhoto();
        $game->setPhoto($form->photo);
      }      

      if (!empty($values['swf_file'])) {
        $game->removeSwf();
        $game->setSwf($form->swf_file);
      }
      
      // Save custom fields
      $customfieldform = $form->getSubForm('fields');
      $customfieldform->setItem($game);
      $customfieldform->saveValues();

      // CREATE AUTH STUFF HERE
      $values = $form->getValues();
      
      // CREATE AUTH STUFF HERE
      foreach ($auth_keys as $auth_key => $auth_default)
      {
        $auth_value = isset($values['auth_'.$auth_key]) ? $values['auth_'.$auth_key] : $auth_default;
        $authMax = array_search($auth_value, $roles);
          
        foreach( $roles as $i => $role )
        {
          $auth->setAllowed($game, $role, $auth_key, ($i <= $authMax));
        }
      }
      
      $db->commit();


      $savedChangesNotice = Zend_Registry::get('Zend_Translate')->_("Your changes were saved.");
      $form->addNotice($savedChangesNotice);
      $customfieldform->removeElement('submit');
      
    }
    catch( Exception $e )
    {
      $db->rollBack();
      throw $e;
    }

    /*
    $db->beginTransaction();
    try {
      // Rebuild privacy
      $actionTable = Engine_Api::_()->getDbtable('actions', 'activity');
      foreach( $actionTable->getActionsByObject($game) as $action ) {
        $actionTable->resetActivityBindings($action);
      }

      $db->commit();
    }
    catch( Exception $e )
    {
      $db->rollBack();
      throw $e;
    }
    */
  }
  
  public function previewAction()
  {
    $this->view->game = $game = Engine_Api::_()->core()->getSubject('game');
  }
  
  public function deleteAction()
  {
    // In smoothbox
    $this->view->game = $game = Engine_Api::_()->core()->getSubject('game');
    // Check post
    if( $this->getRequest()->isPost())
    {
      $db = Engine_Db_Table::getDefaultAdapter();
      $db->beginTransaction();


      try
      {
        $game->delete();
        $db->commit();
        
        Engine_Api::_()->core()->clearSubject();
      }

      catch( Exception $e )
      {
        $db->rollBack();
        throw $e;
      }

      $this->_forward('success', 'utility', 'core', array(
          'smoothboxClose' => 10,
          'parentRefresh'=> 10,
          'messages' => array(Zend_Registry::get('Zend_Translate')->_('Game deleted'))
      ));
    }
  }

  public function deleteselectedAction()
  {
    $this->view->navigation = $navigation = Engine_Api::_()->getApi('menus', 'core')
      ->getNavigation('game_admin_main', array(), 'game_admin_main_manage');
          
    $this->view->ids = $ids = $this->_getParam('ids', null);
    $confirm = $this->_getParam('confirm', false);
    $this->view->count = count(explode(",", $ids));

    // Save values
    if( $this->getRequest()->isPost() && $confirm == true )
    {
      $ids_array = explode(",", $ids);
      foreach( $ids_array as $id ){
        $game = Engine_Api::_()->getItem('game', $id);
        if( $game ) $game->delete();
      }

      return $this->_redirectCustom(array('route'=>'admin_default', 'module'=>'game', 'controller'=>'manage'));
      
    }
  }  
  
  public function updateStatusSelectedAction()
  {
    $this->view->ids = $ids = $this->_getParam('ids', null);
    $confirm = $this->_getParam('confirm', false);
    $status = $this->_getParam('status');
   
    $statuses = Game_Form_Helper::getStatuses();
    $this->view->count = count(explode(",", $ids));

    // Save values
    if( $this->getRequest()->isPost() && array_key_exists($status, $statuses))
    {
      $ids_array = explode(",", $ids);
      foreach( $ids_array as $id ){
        $game = Engine_Api::_()->getItem('game', $id);
        if( $game ) {
          $game->status = $status;
          $game->save();
        }
      }

    }
    
    return $this->_redirectCustom(array('route'=>'admin_default', 'module'=>'game', 'controller'=>'manage'));
    
  }
  
  public function downloadSelectedAction()
  {
    $this->view->ids = $ids = $this->_getParam('ids', null);
    $confirm = $this->_getParam('confirm', false);
    $type = $this->_getParam('type', 'both');
   
    $this->view->count = count(explode(",", $ids));

    // Save values
    if( $this->getRequest()->isPost() && $type)
    {
      $ids_array = explode(",", $ids);
      foreach( $ids_array as $id ){
        $game = Engine_Api::_()->getItem('game', $id);
        
        if( $game ) 
        {
          try 
          {
            if ($type == 'both' || $type == 'swf')
            {
              if ($game->swf_url && Zend_Uri::check($game->swf_url))
              {
                $game_file = Engine_Api::_()->game()->downloadFile($game->swf_url);
                $game->removeSwf();
                $game->setSwf($game_file);
              }
            }
            
            if ($type == 'both' || $type == 'photo')
            {
              if ($game->thumbnail_url && Zend_Uri::check($game->thumbnail_url))
              {
                $photo_file = Engine_Api::_()->game()->downloadFile($game->thumbnail_url);
                $game->removePhoto();
                $game->setPhoto($photo_file);
              }
            }
          }
          catch (Exception $e) {
            // silence
          }
          
        }
      }

    }
    
    return $this->_redirectCustom(array('route'=>'admin_default', 'module'=>'game', 'controller'=>'manage'));
    
  }
  
  public function downloadAction()
  {
    $this->view->game = $game = Engine_Api::_()->core()->getSubject('game');
    
    
    $this->view->can_download_swf = $game->swf_url && Zend_Uri::check($game->swf_url);
    $this->view->can_download_photo = $game->thumbnail_url && Zend_Uri::check($game->thumbnail_url);
    
    $type = $this->_getParam('type');
    
    if( $this->getRequest()->isPost() && $type)
    {
      if ($this->view->can_download_swf)
      {
        if ($type == 'both' || $type == 'swf') {
          $game_file = Engine_Api::_()->game()->downloadFile($game->swf_url);
          $game->removeSwf();
          $game->setSwf($game_file);
        }
      }
      if ($this->view->can_download_photo)
      {
        if ($type == 'both' || $type == 'photo') {
          $photo_file = Engine_Api::_()->game()->downloadFile($game->thumbnail_url);
          $game->removePhoto();
          $game->setPhoto($photo_file);
        }
      }

       
      $this->_forward('success', 'utility', 'core', array(
          'smoothboxClose' => 10,
          'parentRefresh'=> 10,
          'messages' => array(Zend_Registry::get('Zend_Translate')->_('File(s) downloaded'))
      ));   
    }

  }
  
  
  public function removeAction()
  {
    $this->view->game = $game = Engine_Api::_()->core()->getSubject('game');
    
    $this->view->can_remove_swf = $game->swf_url && $game->swf_file_id;
    $this->view->can_remove_photo = $game->thumbnail_url && $game->photo_id;
    
    $type = $this->_getParam('type');
    
    if($this->getRequest()->isPost() && $type)
    {
      if ($this->view->can_remove_swf)
      {
        if ($type == 'both' || $type == 'swf') {
          $game->removeSwf();
        }
      }
      if ($this->view->can_remove_photo)
      {
        if ($type == 'both' || $type == 'photo') {
          $game->removePhoto();
        }
      }

      $game->save();
      
      $this->_forward('success', 'utility', 'core', array(
          'smoothboxClose' => 10,
          'parentRefresh'=> 10,
          'messages' => array(Zend_Registry::get('Zend_Translate')->_('File(s) removed'))
      ));      
    }
    
  }
  
  public function removeSelectedAction()
  {
    $this->view->ids = $ids = $this->_getParam('ids', null);
    $confirm = $this->_getParam('confirm', false);
    $type = $this->_getParam('type', 'both');
   
    $this->view->count = count(explode(",", $ids));

    // Save values
    if( $this->getRequest()->isPost() && $type)
    {
      $ids_array = explode(",", $ids);
      foreach( $ids_array as $id ){
        $game = Engine_Api::_()->getItem('game', $id);
        
        if( $game ) 
        {
          try 
          {
            if ($type == 'both' || $type == 'swf')
            {
              if ($game->swf_url && Zend_Uri::check($game->swf_url))
              {
                $game->removeSwf();
                $game->save();
              }
            }
            
            if ($type == 'both' || $type == 'photo')
            {
              if ($game->thumbnail_url && Zend_Uri::check($game->thumbnail_url))
              {
                $game->removePhoto();
                $game->save();
              }
            }
          }
          catch (Exception $e) {
            // silence
          }
          
        }
      }

    }
    
    return $this->_redirectCustom(array('route'=>'admin_default', 'module'=>'game', 'controller'=>'manage'));
    
  }
}